/* 
泛型接口
*/

 /* 
  1. 声明泛型类型: 在接口名的右侧  <T>   // T K V
  2. 使用泛型: 接口体中
  3. 指定泛型的具体类型: 定义实现时, 接口名的右侧 <具体类型>
  */

interface CRUD<T> {
  data: T[];
  add: (t: T) => number;
  getById: (id: number) => T;
}

interface IUser {
  id: number;
  name: string;
  age: number;
}

class User implements IUser {
  id: number;
  name: string;
  age: number;
  constructor (name: string, age: number) {
    this.name = name
    this.age = age
  }
}


class UserCRUD implements CRUD<IUser> {
  data: IUser[] = [];
  
  add (user: IUser): number {
    const id = Date.now()
    user.id = id
    this.data.push(user)
    return id
  }
  
  getById (id: number): IUser {
    return this.data.find(item => item.id===id)
  }
}

const userCRUD = new UserCRUD()
userCRUD.add(new User('tom', 12))
const id = userCRUD.add(new User('jack', 13))

console.log(userCRUD.data)
console.log(userCRUD.getById(id))